package com.monkeyboy.demo.retry;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

public class Consumer {

    public static void main(String[] args) throws Exception {
        //1.创建消费者Consumer，制定消费者组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
        //2.指定Nameserver地址
        consumer.setNamesrvAddr("192.168.1.140:9876;192.168.1.141:9876");
        //3.订阅主题Topic和Tag
        consumer.subscribe("RetryTopic", "*");
        //设置消费者的重试次数
        consumer.setMaxReconsumeTimes(1);

        //4.设置回调函数，处理消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {

            //接受消息内容
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                try {
                    System.out.println("消息内容：  " + new String(msgs.get(0).getBody()));
                    //生产环境中一般是根据失败次数达到多少次后就返回成功，然后把失败的消息给存入到数据库中，以便后期进行补偿
                    System.out.println("重试次数：  " + msgs.get(0).getReconsumeTimes());
                    System.out.println("队列id: "+msgs.get(0).getQueueId());
                    int i = 1 / 0;
                } catch (Exception e) {
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        //5.启动消费者consumer
        consumer.start();

        System.out.println("消费者启动");
    }
}
